import type { ConfigEnv, UserConfig } from 'vite';
import * as process from 'node:process';
import * as path from 'node:path';
import { merge } from 'lodash-es';
import _defaultConfig from './config';

export default function defineConfig(commonConfig: UserConfig = {}) {
    return async ({ mode }: ConfigEnv) => {
        let defaultConfig;
        let modeConfig;

        try {
            defaultConfig = await import(path.join(process.cwd(), './config/config.ts'));
            if (mode !== 'production') {
                modeConfig = await import(path.join(process.cwd(), `./config/config.${mode}.ts`));
            }
        } catch (e) {
            console.error(`Failed to load config file for mode ${mode}:`, e);
        }

        return merge(_defaultConfig, commonConfig, defaultConfig?.default || {}, modeConfig?.default || {});
    };
}
